#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_libxml2_fun_002.py
@Time:      2024/02/22 11:12:50
@Author:    hongfeng
@Version:   1.0
@Contact:   wb-zhf668260@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    hongfeng
"""

import os
from common.basetest import LocalTest
class Test(LocalTest):
    """
    See tc_libxml2_fun_002.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "libxml2-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > parse_xml.c <<EOF
#include <stdio.h>
#include <libxml/parser.h>
#include <libxml/tree.h>

void print_element_names(xmlNode * a_node) {
    xmlNode *cur_node = NULL;

    for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE) {
            printf("Element name: %s\\n", cur_node->name);
        }
        // 递归处理子节点
        print_element_names(cur_node->children);
    }
}

int main() {
    xmlDoc *doc = NULL;
    xmlNode *root_element = NULL;

    // 初始化libxml2解析器
    xmlInitParser();

    // 解析XML文件
    doc = xmlReadFile("test_002.xml", NULL, 0);
    if (doc == NULL) {
        fprintf(stderr, "Error: could not parse file test_002.xml\\n");
        return -1;
    }

    // 获取根元素
    root_element = xmlDocGetRootElement(doc);

    // 打印所有元素名称
    print_element_names(root_element);

    // 清理并释放资源
    xmlFreeDoc(doc);
    xmlCleanupParser();

    return 0;
}
"""
        self.cmd(cmdline)
        self.cmd("gcc -o parse_xml parse_xml.c `xml2-config --cflags --libs`")
        file_dir = os.path.dirname(__file__)
        self.cmd(f"cp {file_dir}/test.xml ./test_002.xml")

    def test(self):
        ret_c,ret_o = self.cmd("./parse_xml")
        self.assertTrue("Element name: body" in ret_o, 'check output error.')
        
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm parse_xml.c parse_xml test_002.xml")
